const initData = {
    list: JSON.parse(localStorage.getItem('addList')) || []
}

const addReducer = (state = initData, {type, payload}) => {

    switch(type) {

        case 'ADD_LIST':
            return {
                ...state,
                list: payload
            }
        
        case 'ADD_ITEM':

            state.list.push(payload)

            localStorage.setItem('addList', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        case 'DELETE_ITEM':

            state.list.splice(payload, 1)

            localStorage.setItem('addList', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        case 'EDIT_ITEM':

            state.list.forEach((item) => {
                if(item.id === payload.id) {
                    item.name = payload.name
                    item.city = payload.city
                }
            })

            localStorage.setItem('addList', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        default:
            return {
                ...state
            }
    }

}

export default addReducer